/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦]
 * 
 * https://zhiqim.org/project/zhiqim_framework/zhiqim_httpd.htm
 *
 * Zhiqim Httpd is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.httpd.nio;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import org.zhiqim.httpd.HttpInputStream;
import org.zhiqim.httpd.HttpRequestAbs;
import org.zhiqim.kernel.util.Bytes;
import org.zhiqim.kernel.util.Urls;
import org.zhiqim.kernel.util.Zips;

/**
 * HTTP NIO请求类，NIO特有的处理方式
 *
 * @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
 */
public class HttpNioRequest extends HttpRequestAbs
{
    private byte[] contentBytes;
    private int offset;
    
    /** 构造函数 */
    public HttpNioRequest (HttpNioHeader header)
    {
        super(header);
    }
    
    /***********************************************************************/
    //解析请求头、内容、会话和证书等
    /***********************************************************************/
    
    /**
     * 分析请求内容
     * 
     * @exception IOException IO异常
     */
    public boolean parseContent() throws IOException
    {
        //第十二步，解析内容流
        int cLen = getContentLength();
        if (cLen <= 0)
        {//无内容
            bis = new ByteArrayInputStream(new byte[0]);
            return true;
        }
   
        //有内容
        if (contentBytes == null)
        {
            contentBytes = new byte[cLen];
            offset = 0;
        }
        
        byte[] buf = ((HttpInputStream)input).read(cLen - offset);
        if (buf != null && buf.length > 0)
        {
            offset = Bytes.putBytes(contentBytes, offset, buf);
        }
        
        if (offset != cLen)
            return false;
        
        bis = new ByteArrayInputStream(contentBytes, 0, cLen);
        
        if (isRequestGZip())
            bis = Zips.unGZip(bis);
        
        if (_POST_.equals(header.getMethod()) && _APPLICATION_X_WWW_FORM_.equals(header.getMimeType()))
        {//form表单提交方式要解析到内容参数表中
            String line = new String(contentBytes, header.getCharacterEncoding());
            Urls.toMap(line, cntParamMap.instance(), header.getCharacterEncoding());
        }
        
        return true;
    }

    /***********************************************************************/
    //destroy
    /***********************************************************************/
    
    /** 销毁 */
    public void destroy()
    {
        super.destroy();
        
        if (contentBytes != null)
            contentBytes = null;
    }
}
